<?php
namespace forpc\controllers;


use Yii;
use common\components\Controller;
use common\components\PageView;
use common\models\Correct;
use common\models\Lexicon;
use common\models\Tag;


/**
 * 词库
 */
class RandomController extends Controller{

    public $enableCsrfValidation = false;

    /**
     * 随机词库
     * @return string
     */
    public function actionIndex(){

        $c1 = isset($_GET["c1"]) ? intval($_GET["c1"]) : 0;
        $c2 = isset($_GET["c2"]) ? intval($_GET["c2"]) : 0;
        $c3 = isset($_GET["c3"]) ? intval($_GET["c3"]) : 0;
        $cid = isset($_GET["cid"]) ? intval($_GET["cid"]) : 0;
        $correct = isset($_GET["correct"]) ? addslashes($_GET["correct"]) : "0-15";
        $tags = isset($_GET["tags"]) ? addslashes($_GET["tags"]) : "";
        $fav = isset($_GET["fav"]) ? addslashes($_GET["fav"]) : "all";
        $refresh = (isset($_GET["refresh"]) && $_GET["refresh"]==1) ? 1 : 0;

        $categorys = \common\models\Category::getData();
        //print_r($categorys);

        $treeData = \common\models\Category::getTree($categorys);
        //print_r($treeData);

        $where = ' WHERE TRUE';
        $con1 = ($c1 == 0) ? "" : " AND k.c1=".$c1;
        $con1 = ($c2 == 0) ? $con1 : " AND k.c2=".$c2;
        $con_tags = Tag::getSqlCondition($tags, 'w');
        $where = $where.$con_tags;

        $db = Yii::$app->db;
        $session = \Yii::$app->session;

        if($refresh==1){
            $session->remove('random_ids');
        }

        $session_ids = $session->get('random_ids');
        if(empty($session_ids)){

            $sql = "SELECT w.id FROM {{%english}} AS w ".
                "LEFT JOIN `en_user_practices` AS f ON w.id=f.id ".
                "JOIN (SELECT CEIL(RAND() * (SELECT MAX(id) FROM {{%english}} AS w ".$where.")) AS id) AS r2 ".
                "WHERE w.id >= r2.id".preg_replace('/ WHERE TRUE/','',$where)." ORDER BY w.id ASC LIMIT 1";
            //echo $db->createCommand($sql)->getRawSql();exit;

            $ids = [];
            for($i=0; $i<20; $i++){
                $ids[] =  $db->createCommand($sql)->queryScalar();
            }
            shuffle($ids);
            $session = \Yii::$app->session;
            $session->set('random_ids' ,$ids);
        }else{
            $ids = $session_ids;
        }
//        echo '<pre>';
//        print_r($ids);exit;

        $ids = array_unique($ids);
        $ids_str = implode(',', $ids);
        //var_dump($ids_str);

        $where = ' WHERE w.id IN('.$ids_str.')';
        $order = " ORDER BY FIELD(w.`id`, ".$ids_str.")";
        //echo $where;exit;

        $sql = 'SELECT w.id, w.cid, '.
            't.name AS cname, c2.name AS cname2, w.word, w.ipa_en, w.ipa_us, w.trans, f.id AS f_id FROM {{%english}} AS w '.
            'LEFT JOIN {{%knowledge_cate}} AS t ON w.c1=t.id '.
            'LEFT JOIN {{%knowledge_cate}} AS c2 ON w.c2=c2.id '.
            'LEFT JOIN {{%user_practices}} AS f ON w.id=f.id '.
            $where.$order;

        $words = $db->createCommand($sql)->queryAll();
        //print_r($words);exit;

        $data = [
            "c1" => $c1,
            "c2" => $c2,
            "c3" => $c3,
            "cid" => $cid,
            "categorys" => $categorys,
            'treeData' => $treeData,
            "correct" => $correct,
            "tags" => $tags,
            "fav" => $fav,
            "words" => $words,
            "mobile"=>1,
        ];

        return $this->renderPartial('index', $data);

    }

    public function actionAsyncRight(){
        header("Content-Type;text/html; charset=utf-8");

        $id = isset($_POST["id"]) ? intval($_POST["id"]) : 0;
        $lexicon = isset($_POST["lexicon"]) ? addslashes($_POST["lexicon"]) : "";

        if(empty($id)){
            exit(json_encode(["code"=>-1, "info"=>"缺少参数知识ID"], JSON_UNESCAPED_UNICODE));
        }

        if(empty($lexicon)){
            exit(json_encode(["code"=>-1, "info"=>"缺少参数：lexicon"], JSON_UNESCAPED_UNICODE));
        }

        $db = Yii::$app->db;

        $lexiconConfig = Lexicon::getConfig($lexicon);
        $tableName = $lexiconConfig['tableName'];
        $knowledge = $db->createCommand("SELECT last_right_time, `right` FROM $tableName WHERE wid=$id")->queryOne();

        //print_r($knowledge);exit;
        $isHave = empty($knowledge) ? false : true;
        $last_right_time = isset($knowledge["last_right_time"]) ? $knowledge["last_right_time"] : 0;
        $right = isset($knowledge["right"]) ? $knowledge["right"] : 0;



        $curtime = time();

        if($right <8){
            if($last_right_time+16*3600 > $curtime){
                exit(json_encode(["code"=>-2, "info"=>"距离上次操作不超过16小时，请稍后再试"], JSON_UNESCAPED_UNICODE));
            }
        }else if($right <16){
            if($last_right_time+64*3600 > $curtime){
                exit(json_encode(["code"=>-2, "info"=>"距离上次操作不超过64小时，请稍后再试"], JSON_UNESCAPED_UNICODE));
            }
        }else if($right <18){
            if($last_right_time+7*24*3600 > $curtime){
                exit(json_encode(["code"=>-2, "info"=>"距离上次操作不超过一周，请稍后再试"], JSON_UNESCAPED_UNICODE));
            }
        }else if($right >=18){
            if($last_right_time+30*24*3600 > $curtime){
                exit(json_encode(["code"=>-2, "info"=>"距离上次操作不超过一个月，请稍后再试"], JSON_UNESCAPED_UNICODE));
            }
        }

        $conx = ($right >= 17) ? ", `graduated`=1" : "";

        if($isHave){
            $sql = "UPDATE $tableName SET last_right_time=".time().", `right`=`right`+1".$conx." WHERE wid=$id";
            $line = $db->createCommand($sql)->execute();
            if($line == 1){
                exit(json_encode(["code"=>1, "info"=>"更新成功"], JSON_UNESCAPED_UNICODE));
            }else{
                exit(json_encode(["code"=>-3, "info"=>"更新失败"], JSON_UNESCAPED_UNICODE));
            }
        }else{//插入
            $data = [
                'wid' => $id,
                'last_right_time' => time(),
                'right' => $right+1,
            ];
            $line = $db->createCommand()->insert($tableName, $data)->execute();
            if($line == 1){
                exit(json_encode(["code"=>1, "info"=>"插入成功"], JSON_UNESCAPED_UNICODE));
            }else{
                exit(json_encode(["code"=>-3, "info"=>"插入失败"], JSON_UNESCAPED_UNICODE));
            }
        }

    }






}
